﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using LDSP.BRL;
using System.Data;
using System.Text.RegularExpressions;
using ImplementationInitialization.Constants;
using System.IO;

namespace ImplementationInitialization
{
    public class FinalExposureDraftImport : FinalImport
    {
        protected override void ImportSheet(string filename, DataTable dt, string sheetName)
        {
            Import(filename, dt, 0, sheetName);
        }

        protected override void Import(string filename, System.Data.DataTable dt, int catalogID, string sheetName)
        {
            IDictionary<string, ExposureDraft> edDic = BaseDataInitial.GetExistedExposureDraft();
            IDictionary<string, Catalog> catalogDic = BaseDataInitial.GetCatalogs();
            foreach (DataRow row in dt.Rows)
            {
                ExposureDraft ed = null;

                string name = row.ItemArray.Length > 1 && row[1] != null ? row[1].ToString() : string.Empty;
                name = GetChineseName(name);

                try
                {
                    Logger.WriteLog("====Begin Import Exposure Draft : " + name);

                    if (edDic.ContainsKey(name))
                    {//Update codification.
                        ed = edDic[name];
                        SetCodification(ed, catalogID, row, name);

                        ed.Update();

                        WriteImportItemResult(name, filename, sheetName, "更新", true);
                    }
                    else
                    {//Add codification.
                        ed = new ExposureDraft();
                        ed.Name = name;

                        SetCodification(ed, catalogID, row, name);

                        ed.Add();

                        //加入到缓存.
                        BaseDataInitial.AddExposure(edDic, ed);
                        _newExposureDrafts.Add(ed);

                        WriteImportItemResult(name, filename, sheetName, "添加", true);
                    }
                }
                catch (Exception ex)
                {
                    string message = "Error import : " + "File Name : " + filename + " Codification : " + ed.Name
                        + "\n" + "Message : " + ex.Message;
                    Logger.WriteLog(message);

                    WriteImportItemResult(name, filename, sheetName, message, false);
                }

                Logger.WriteLog("====End Import Codification : " + name);
            }
        }

        protected override void UpdateAttachement(string sourceDir, string desDir, string root)
        {
            IDictionary<string, ExposureDraft> edDic = BaseDataInitial.GetExistedExposureDraft();
            foreach (string filePath in Directory.GetFiles(sourceDir))
            {
                string fileName = Path.GetFileName(filePath);
                string edName = AnalyseCodName(fileName);

                try
                {
                    if (edDic.ContainsKey(edName))
                    {
                        if (string.IsNullOrEmpty(edDic[edName].FileExtension) || _isForceImport)
                        {
                            edDic[edName].CreateNewFile(fileName);
                            edDic[edName].Update();

                            File.Copy(sourceDir + "\\" + fileName, desDir + "\\" + edDic[edName].FileExtension, true);

                            WriteImportAttachmentResult(fileName, "", true);
                        }
                        else
                        {
                            WriteImportAttachmentResult(fileName, "对应征求意见稿的附件已添加", false);
                        }

                    }
                    else
                    {
                        WriteImportAttachmentResult(fileName, "系统里没有对应的征求意见稿", false);
                    }
                }
                catch (Exception ex)
                {
                    string message = "Error update attachment for Codification : " + edName + " File : " + fileName + " Exception : " + ex.Message;
                    Logger.WriteLog(message);
                    WriteImportAttachmentResult(fileName, message, false);
                }
            }

            foreach (string dir in Directory.GetDirectories(sourceDir))
            {
                string desdir = desDir + "\\" + Path.GetFileName(dir);
                Directory.CreateDirectory(desdir);

                UpdateAttachement(dir, desdir, root);
            }
        }

        protected override string AnalyseCodName(string fileName)
        {
            //string codName = fileName.IndexOf(".") > -1 ? fileName.Substring(0, fileName.IndexOf(".")) : fileName;

            ////最后一个下划线后面的是日期，其他是法规名。
            //if (fileName.Contains("_"))
            //{
            //    codName = fileName.Substring(0, fileName.LastIndexOf("_"));
            //}

            //return codName;
            return base.AnalyseCodName(fileName);
        }

        protected override void WriteImportAttachmentResult(string fileName, string message, bool success)
        {
            ImportResult.AddAttachmentResult(fileName, DocType.征求意见稿, message, success);
        }

        protected override void WriteImportItemResult(string codName, string excel, string sheet, string message, bool success)
        {
            ImportResult.AddItemResult(excel, DocType.征求意见稿, sheet, codName, message, success);
        }

        private void SetCodification(ExposureDraft ed, int catalogID, DataRow row, string name)
        {
            string referenceNumber = string.Empty;

            int i_organizaiton = 2;
            int i_issue_date = 4;
            int i_end_date = 5;
            int i_summary = 6;

            //发布机构
            ed.Organization = row[i_organizaiton] != null ? row[i_organizaiton].ToString() : string.Empty;

            //发布日期
            DateTime releaseDT = DateTime.MinValue;
            if (row[i_issue_date] != null && DateTime.TryParse(row[i_issue_date].ToString(), out releaseDT))
            {
                releaseDT = DateTime.Parse(row[i_issue_date].ToString());
            }
            if (releaseDT != DateTime.MinValue)
            {
                ed.ReleaseDT = releaseDT;
            }

            //实施日期
            DateTime endDT = DateTime.MinValue;
            if (row[i_end_date] != null && DateTime.TryParse(row[i_end_date].ToString(), out endDT))
            {
                endDT = DateTime.Parse(row[i_end_date].ToString());
            }
            if (endDT != DateTime.MinValue)
            {
                ed.EndDT = endDT;
            }

            //法规概述
            ed.Summary = row[i_summary] != null ? row[i_summary].ToString() : string.Empty;

            //更新日期
            ed.UploadDT = this.UploadDT;
        }
    }
}
